package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmSensitiveDto;
import com.heima.model.wemedia.dtos.WmQuerySensitiveDto;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmSensitiveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 11494
 * @version 1.0 敏感词数据处理业务层
 * @project heima-leadnews-group
 * @date 2024/1/25 09:49:03
 */
@Service
@Slf4j
@Transactional
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements WmSensitiveService {
    @Autowired
    private CacheService cacheService;

    /**
     * 功能描述：修改敏感词
     *
     * @param wmSensitiveDto
     * @return {@link ResponseResult }
     * @author sungang
     * @date 2024/01/25  11:59
     */

    @Override
    public ResponseResult updateSensitives(WmSensitiveDto wmSensitiveDto) {
        //参数校验
        if (wmSensitiveDto == null || "".equals(wmSensitiveDto) ||
                wmSensitiveDto.getId() == null || "".equals(wmSensitiveDto.getId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //数据处理
        WmSensitive sensitive = getById(wmSensitiveDto.getId());
        if (sensitive == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmSensitive wmSensitive = new WmSensitive();
        BeanUtils.copyProperties(wmSensitiveDto, wmSensitive);
        wmSensitive.setCreatedTime(new Date());
        updateById(wmSensitive);
        //添加到redis
        addToRedis();
        //结果封装
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 功能描述：删除敏感词
     *
     * @param id
     * @return {@link ResponseResult }
     * @author sungang
     * @date 2024/01/25  11:43
     */

    @Override
    public ResponseResult deleteSensitives(Integer id) {
        //参数校验
        if (id == null || "".equals(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //数据处理
        WmSensitive sensitive = getById(id);
        if (sensitive == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        removeById(id);
        //添加到redis
        addToRedis();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 功能描述：添加敏感词
     *
     * @param wmSaveSensitiveDto
     * @return {@link ResponseResult }
     * @author sungang
     * @date 2024/01/25  11:13
     */

    @Override
    public ResponseResult saveSensitives(WmSensitiveDto wmSaveSensitiveDto) {
        //阐述校验
        if (wmSaveSensitiveDto == null || "".equals(wmSaveSensitiveDto.getSensitives()) || wmSaveSensitiveDto.getSensitives() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //数据处理
        //判断敏感词数据库是否已存在
        LambdaQueryWrapper<WmSensitive> wrapper = Wrappers.<WmSensitive>lambdaQuery().eq(WmSensitive::getSensitives, wmSaveSensitiveDto.getSensitives());
        WmSensitive wmSensitive = getOne(wrapper);
        if (wmSensitive == null) {
            WmSensitive sensitive = new WmSensitive();
            sensitive.setSensitives(wmSaveSensitiveDto.getSensitives());
            sensitive.setCreatedTime(new Date());
            //保存到数据库
            save(sensitive);
            addToRedis();
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
    }


    /**
     * 功能描述：敏感词分页查询
     *
     * @param wmSensitiveDto
     * @return {@link ResponseResult }
     * @author sungang
     * @date 2024/01/25  10:03
     */

    @Override
    public ResponseResult querySensitives(WmQuerySensitiveDto wmSensitiveDto) {
        //参数校验
        if (wmSensitiveDto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //数据处理
        wmSensitiveDto.checkParam();
        //分页条件构建,添加分页拦截器-
        Page<WmSensitive> page = new Page<>(wmSensitiveDto.getPage(), wmSensitiveDto.getSize());
        //分页条件查询
        LambdaQueryWrapper<WmSensitive> wrapper = Wrappers.<WmSensitive>lambdaQuery()
                .like(wmSensitiveDto.getName() != null && !("".equals(wmSensitiveDto.getName())),
                        WmSensitive::getSensitives, wmSensitiveDto.getName())
                .orderByDesc(WmSensitive::getCreatedTime);
        page(page, wrapper);
        //结果返回封装
        PageResponseResult result = new PageResponseResult((int) page.getCurrent()
                , (int) page.getSize(), (int) page.getTotal());
        result.ok(AppHttpCodeEnum.SUCCESS.getCode(), page.getRecords(), AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return result;
    }
    // 将数据库中的敏感词添加到redis缓存
    private void addToRedis() {
        cacheService.delete("sensitives");
        List<WmSensitive> sensitivesList = list(null);
        if (sensitivesList.size() > 0 && sensitivesList != null) {
            cacheService.set("sensitives", JSON.toJSONString(sensitivesList));
        }
    }
}
